package com.heaven.event;

import com.heaven.service.VideoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UpToMinioEventListener implements ApplicationListener<UpToMinioEvent> {
    @Resource
    private VideoService videoService;

    /**
     * 响应 服务端上传到 minio 事件，注意在服务端传递完毕后minio并不会立马将文件完整保存
     * 而是要进过一段时间的处理，在更新字段状态时需要按照实际检验
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(UpToMinioEvent event) {
        // 更新 video 表的 status 字段
        if(videoService.isVideoExistInMinio(event.getObjectName())) {
            Query query = new Query();
            query.addCriteria(Criteria.where("md5").is(event.getMd5())
                    .andOperator(Criteria.where("is_in_minio").is(0)));

            Update update = Update.update("is_in_minio", 1);
            videoService.updateMulti(query, update);
        }
    }
}
